/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* SdProjectSuperviseService
* SD项目督办
*
* 修改纪录
* 2021-12-08 版本：1.0 wangxinhua 创建。
* @version 版本：1.0
* @author 作者：wangxinhua
* 创建日期：2021-12-08
*/
package com.topscomm.gpm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.cbo.pojo.CboApprovalFlowInsEntity;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.service.ICboApprovalFlowInsService;
import com.topscomm.cbo.service.ICboApprovalNodeInsService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.gpm.pojo.GpmProjectEntity;
import com.topscomm.gpm.pojo.GpmProjectSuperviseEntity;
import com.topscomm.tap.common.DatacodeCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.gpm.service.IGpmProjectSuperviseService;
import com.topscomm.gpm.service.impl.auto.GpmProjectSuperviseServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service(value = "gpmProjectSuperviseService")
@Scope(value = "singleton")
public class GpmProjectSuperviseService extends GpmProjectSuperviseServiceAuto implements IGpmProjectSuperviseService {
    @Autowired
    protected GpmProjectService gpmProjectService;
    @Autowired
    protected DatacodeCache datacodeCache;
    @Autowired
    protected ICboApprovalFlowInsService cboApprovalFlowInsService;
    @Autowired
    protected ICboUserService cboUserService;
    @Autowired
    protected ICboApprovalNodeInsService cboApprovalNodeInsService;
    /**
     * @author: zhangjunyao
     * @date: 2021-12-20
     * @param entity
     * @throws ServiceException
     * @description:督办编号生成
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity){
        super.beforeInsert(entity);
        try {
            if (entity.getId() <= 0) {
                long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
                // 赋值Id
                entity.setId(arrayId[0]);
                // 赋值单号
                String docNo = String.valueOf(arrayId[0]);
                docNo = docNo.substring(0, 6) + docNo.substring(9);
                entity.setValue(GpmProjectSuperviseEntity.FieldDocno, docNo);
                // 赋值督办单号
                String format = "PS";
                // 获取项目级别
                String projectId = ConvertUtil.convertToString(entity.getValue("projectid"));
                GpmProjectEntity projectEntity = gpmProjectService.queryById(projectId);
                String projectLevel = projectEntity.getProjectlevel();
                projectLevel = datacodeCache.getValueDynamic("GpmProjectLevel", projectLevel, "code", "name");
                format = format + projectLevel;
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                format = format + simpleDateFormat.format(new Date());
                String flowcode = docNo.substring(docNo.length() - 3);
                format = format + flowcode;
                entity.setValue(GpmProjectSuperviseEntity.FieldSupervisecode, format);
            }
        } catch(Exception ex) {
            throw new ServiceException(ex + "id或单号生成失败");
        }
    }

    /**
     *
     * @description: 项目监管页面查询督办情况
     * @param
     * @throws Exception
     * @author: zhangjunyao
     * @date: 2021-12-27
     * @modify:
     */
    @Transactional(rollbackFor = Exception.class)
    public void getSuperviseList(List<Map<String, Object>> tempList) {
        StringBufferProxy sql = new StringBufferProxy();
        String projectIds = tempList.stream().map(item -> ConvertUtil.convertToString(item.get("id")))
                .collect(Collectors.joining("','", "'", "'"));
        // 查询督办表获取所有项目的督办情况
        sql.appendSingle("projectid in ({0}) order by createon", projectIds);
        List<Map<String, Object>> superviseMap = this.queryMapByWhere(sql.toString());
        if (superviseMap.isEmpty()) {
            return;
        }
        // 转为以projectcode区分的督办list
        Map<String, List<Map<String, Object>>> dataMap = superviseMap.stream()
                .collect(Collectors.groupingBy(map -> ConvertUtil.convertToString(map.get("projectid"))));
        for (Map<String, Object> mapRow : tempList) {
            String projectId = ConvertUtil.convertToString(mapRow.get("id"));
            if (dataMap.containsKey(projectId)) {
                mapRow.put("superviselist", dataMap.get(projectId));
            }
        }
    }

    /**
     * @author: zhangjunyao
     * @date: 2021-12-31
     * @param: mapRow
     * @param: datacodeCache
     * @description:重写setDispFields
     * @return: void
     * @modify:
     */
    @Override
    public void setDispFields(Map<String, Object> mapRow, DatacodeCache datacodeCache) {
        super.setDispFields(mapRow, datacodeCache);
        String temp;
        if (mapRow.get("superviseobject") != null) {
            temp = mapRow.get("superviseobject").toString();
            if(StringUtil.isNumeric(temp)) {
                mapRow.put("dispsuperviseobject", datacodeCache.getValueDynamic("MpmSuperviseObject", temp, "code", "name"));
            } else {
                mapRow.put("dispsuperviseobject", temp);
            }
        }
    }

    /**
     *
     * @description: 插入App消息
     * @param
     * @throws Exception
     * @author: zhangjunyao
     * @date:
     * @modify:
     */
    public Map<String, Object> insertMessageApp(String usercode, String extendfield1, String content, long sourceid, String sourcetype, int sendtype) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("usercode", usercode);
        map.put("extendfield1", extendfield1);
        map.put("content", content);
        map.put("sourceid", sourceid);
        map.put("sourcetype", sourcetype);
        map.put("sendtype", sendtype);
        return map;
    }

    /**
     * @Description:    消息迁移——组装App消息
     * @Author:         wuyuyang
     * @Return:         java.util.Map<java.lang.String,java.lang.Object>
     * @exception:
     * @Date:           13/10/2023 下午3:50
     * @Version:        1.0
     **/
    public Map<String, Object> insertMessageApporMsg(String usercode, String username, String extendfield1, String content, long sourceid, String sourcetype, int sendtype) {
        HashMap<String, Object> map = new HashMap<>();
//        map.put("usercode", usercode);
        map.put("receivercode", usercode);
        map.put("receivername", username);
        map.put("extendfield1", extendfield1);
        map.put("content", content);
        map.put("sourceid", sourceid);
        map.put("sourcetype", sourcetype);
        map.put("sendtype", sendtype);
        return map;
    }

    /**
     * @Description:    消息迁移——组装App消息
     * @Author:         wuyuyang
     * @Return:         java.util.Map<java.lang.String,java.lang.Object>
     * @exception:
     * @Date:           13/10/2023 下午3:42
     * @Version:        1.0
     **/
    public Map<String, Object> insertMessageAppForMsg(String usercode, String username, String extendfield1, String content, long sourceid, String sourcetype, int sendtype) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("receivercode", usercode);
        map.put("receivername", username);
//        map.put("usercode", usercode);
        map.put("extendfield1", extendfield1);
        map.put("content", content);
        map.put("sourceid", sourceid);
        map.put("sourcetype", sourcetype);
        map.put("sendtype", sendtype);
        return map;
    }

    /**
     * @author: zhangjunyao
     * @date:
     * @description: 插入系统消息
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @modify:
     */
    public Map<String, Object> insertMessageSys(String usercode, String username, String title, String content, long sourceid, String sourcetype) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("receivercode", usercode);
        map.put("receivername", username);
        map.put("subject", title);
        map.put("content", content);
        map.put("sourceid", sourceid);
        map.put("sourcetype", sourcetype);
        return map;
    }
    /**
     * @author: zhangjunyao
     * @date:
     * @description: 插入系统消息
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @modify:
     */
    public void updateSuperviseUser(Map<String, Object> paraMap) {
        // 更新督办模块信息
        this.update(paraMap);
        // 更新maintitle
        StringBufferProxy mailtitle = new StringBufferProxy();
        mailtitle.appendSingle("{0}{1}于{2}提交项目督办申请,单据编号{3}! ", paraMap.get("deptname"), paraMap.get("username"),
                DateUtil.dateToString(new Date(), "yyyy-MM-dd"), paraMap.get("docno"));
        // 更新flowins表的maintitle和extendFields3
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" sourceid = '{0}' and sourcetype = 'GpmProjectSupervise' and enabled = 1 ", paraMap.get("id"));
        CboApprovalFlowInsEntity cboApprovalFlowInsEntity = cboApprovalFlowInsService.queryObjectByWhere(sql.toString());
        if (ObjectUtil.isEmpty(cboApprovalFlowInsEntity)) {
            return;
        }
        cboApprovalFlowInsEntity.setMaintitle(mailtitle.toString());
        cboApprovalFlowInsEntity.setExtendfield3(ConvertUtil.convertToString(paraMap.get("usercode")));
        cboApprovalFlowInsService.updateEntity(cboApprovalFlowInsEntity);
        // 更新nodeins表的maintitle
        sql.clear();
        sql.appendSingle(" enabled = 1 and state = 1 and sourceid = '{0}' and sourcetype = 'GpmProjectSupervise' ", paraMap.get("id"));
        List<CboApprovalNodeInsEntity> cboApprovalNodeInsEntities = cboApprovalNodeInsService.queryByWhere(sql.toString());
        if (CollectionUtil.isEmpty(cboApprovalNodeInsEntities)) {
            return;
        }
        List<BasicEntity> basicEntities = new ArrayList<>();
        for (CboApprovalNodeInsEntity cboApprovalNodeInsEntity : cboApprovalNodeInsEntities) {
            cboApprovalNodeInsEntity.setMaintitle(mailtitle.toString());
            basicEntities.add(cboApprovalNodeInsEntity);
        }
        cboApprovalNodeInsService.updateBatch(basicEntities);
    }
}
